const HtmlWebpackPlugin = require('html-webpack-plugin');

class HotReload {
  apply(compiler) {
    compiler.hooks.compilation.tap('HotReload', (compilation) => {
      HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync('HotReload', (data, cb) => {
        // 热加载
        const i = data.html.lastIndexOf('</body>');
        data.html =
          data.html.slice(0, i) +
          '    <script>(function(){new WebSocket(`ws://${window.location.host}/ws`).addEventListener("message", function(event){if(event.data.indexOf("invalid")!= -1){window.location.reload()}})})()</script>\r\n' +
          data.html.slice(i);
        cb(null, data);
      });
    });
  }
}

module.exports = HotReload;
